package com.mytaobao.main.cart;


import com.baseproject.RxSubscriber;
import com.baseproject.mvp.MvpBasePresenter;
import com.baseproject.util.LogUtils;
import com.mytaobao.main.cart.func.cart.ItemCommodity;
import com.mytaobao.requestlayer.AppRequest;

import java.util.ArrayList;
import java.util.List;

//import static com.google.common.base.Preconditions.checkNotNull;


/**
 * 将Presenter分离为基础方法和业务方法
 */
public class CartPresenter extends MvpBasePresenter<CartFragment> implements CartContract.ICartPresenter {

    public CartPresenter() {

    }

    @Override
    public void start() {
        if (null == mCommodities || mCommodities.size() == 0) {
            loadCommodity();
        } else {
            if(isAttachView()) {
                getView().setCommodities(mCommodities);
            }
        }
    }

    List<List<ItemCommodity>> mCommodities;

    @Override
    public void loadCommodity() {
        final long startTime = System.currentTimeMillis();
        subscriptions.add(AppRequest.getCommodity()
                      .subscribe(new RxSubscriber<List<ItemCommodity>>(getView()) {
                          @Override
                          public void _onNext(List<ItemCommodity> itemCommodities) {
                              LogUtils.d("load itemCommodities: spendTime = " + (System.currentTimeMillis() - startTime));
                              mCommodities = covertFromResponseToViewNeed(itemCommodities);
                              if (isAttachView()) {
                                  getView().setCommodities(mCommodities);
                              }
                          }
                      }));
    }

    protected List<List<ItemCommodity>> covertFromResponseToViewNeed(List<ItemCommodity> itemCommodities){
        List<List<ItemCommodity>> result = new ArrayList<List<ItemCommodity>>();
        int size = itemCommodities.size();
        for (int i = 0; i < size;) {
            List<ItemCommodity> subResult = new ArrayList<>();
            ItemCommodity current = itemCommodities.get(i);
            subResult.add(current);
            if (i == size -1) break;;
            ItemCommodity next = itemCommodities.get(++i);
            while (current.getBelongToShopId() == next.getBelongToShopId() && i < size) {
                subResult.add(next);
                if (i == size -1) break;;
                next = itemCommodities.get(++i);
            }
            result.add(subResult);
        }
        return result;
    }
}
